<?php

namespace HiCommon\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Base extends Model
{

    use SoftDeletes;

    public $hi_display_api = false;

    public $hi_db_prefix = 'car_';

    /**
     * 表字段注释
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    protected function table_field_api()
    {
        if ($this->hi_display_api === false) {
            $arr_data = null;
        }
        else{
            $s_full_table = $this->hi_db_prefix . $this->table;
            $columns      = \DB::getDoctrineSchemaManager()
                               ->listTableColumns($s_full_table);
            $arr_data     = [];
            foreach ($columns as $column) {
                $arr_data[$column->getName()] = $column->getComment();
            }
        }

        return $arr_data;
    }

    /**
     * 获取表字段
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function table_field_keys()
    {
        $s_full_table = $this->hi_db_prefix . $this->table;
        $columns      = \DB::getDoctrineSchemaManager()
                           ->listTableColumns($s_full_table);
        $arr_data     = [];
        foreach ($columns as $column) {
            $arr_data[] = $column->getName();
        }
        return $arr_data;
    }

    /**
     * state 注释
     *
     * @param $value
     *
     * @return string
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function state_api($value)
    {
        $s_string = collect($value)
          ->map(function ($value, $key) {
              if ($value['id'] == -99) {
                  return $value['name'] . ':';
              }
              else {
                  return $value['id'] . '-' . $value['name'];
              }

          })
          ->implode(' ');

        return $s_string;
    }

    /**
     * 获取state值和注释的集合
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function hi_arr_state_name($arr_data)
    {
        return collect($arr_data)
          ->map(function ($value, $key) {
              $arr_state = $value[$this->$key];
              $data      = ['name' => $arr_state['name']];
              if ($this->hi_display_api === true) {
                  $data['api'] = $this->state_api($value);
              }
              return $data;
          })
          ->toArray();
    }

    /**
     * 获取state值和注释的集合
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function hi_arr_state_display_name($arr_data)
    {

        return collect($arr_data)
          ->map(function ($value, $key) {
              $data = collect($value)
                        ->where('id', $this->$key)
                        ->first()['name'];
              return $data;
          })
          ->toArray();
    }




    ///////// DB操作


    //
    //    /**
    //     * 获取所有数据
    //     *
    //     * @param $query
    //     * @param $arr_option
    //     *
    //     * @return mixed
    //     * @author wumengmeng <wu_mengmeng@foxmail.com>
    //     */
    //    public function commonget($arr_option = [])
    //    {
    //        $arr_option = self::config_option($arr_option);
    //        return self::with($arr_option['with'])
    //                   ->where($arr_option['where'])
    //                   ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
    //                   ->select($arr_option['field'])
    //                   ->get();
    //    }
    //
    //    /**
    //     * 分页
    //     *
    //     * @param $query
    //     * @param $arr_option
    //     *
    //     * @return mixed
    //     * @author wumengmeng <wu_mengmeng@foxmail.com>
    //     */
    //    public function commonpage($arr_option = [])
    //    {
    //        $arr_option = self::config_option($arr_option);
    //        return self::with($arr_option['with'])
    //                   ->where($arr_option['where'])
    //                   ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
    //                   ->select($arr_option['field'])
    //                   ->withCount($arr_option['withCount'])
    //                   ->paginate($arr_option['n_per_page']);
    //    }
    //
    //    /**
    //     * 查询一条数据
    //     *
    //     * @param       $query
    //     * @param int   $nId
    //     * @param array $arr_option
    //     *
    //     * @return mixed
    //     * @author wumengmeng <wu_mengmeng@foxmail.com>
    //     */
    //    public function commonfind(int $nId, $arr_option = [])
    //    {
    //        $arr_option = self::config_option($arr_option);
    //
    //        return self::with($arr_option['with'])
    //                   ->select($arr_option['field'])
    //                   ->find($nId);
    //    }
    //
    //    /**
    //     * 查询一条数据
    //     *
    //     * @param       $query
    //     * @param int   $nId
    //     * @param array $arr_option
    //     *
    //     * @return mixed
    //     * @author wumengmeng <wu_mengmeng@foxmail.com>
    //     */
    //    public function commonfirst($arr_option = [])
    //    {
    //        $arr_option = self::config_option($arr_option);
    //
    //        return self::orderBy($arr_option['order']['key'], $arr_option['order']['value'])
    //                   ->with($arr_option['with'])
    //                   ->select($arr_option['field'])
    //                   ->first();
    //    }
    //
    //    /**
    //     * 删除数据
    //     *
    //     * @param $query
    //     *
    //     * @return mixed
    //     * @author wumengmeng <wu_mengmeng@foxmail.com>
    //     */
    //    public function commondelete(bool $bool = false)
    //    {
    //        if ($bool === true) {
    //            //物理删除
    //            return self::forceDelete();
    //
    //        }
    //        else {
    //            //软删除
    //            return self::delete();
    //        }
    //    }
    //
    //    /**
    //     * 分页-api
    //     *
    //     * @param $query
    //     * @param $arr_option
    //     *
    //     * @return mixed
    //     * @author wumengmeng <wu_mengmeng@foxmail.com>
    //     */
    //    public function apipage($arr_option = [])
    //    {
    //        $arr_option = self::config_option($arr_option);
    //        return self::with($arr_option['with'])
    //                   ->where($arr_option['where'])
    //                   ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
    //                   ->select($arr_option['field'])
    //                   ->paginate($arr_option['n_per_page']);
    //
    //    }


    ///////// DB操作-原scope

    /**
     * 基础config
     *
     * @param $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function config_option($arr_option)
    {
        $arr_common_config = common_config();
        if (empty($arr_option['with'])) {
            $arr_option['with'] = $arr_common_config['with'];
        }
        if (empty($arr_option['where'])) {
            $arr_option['where'] = $arr_common_config['where'];
        }
        if (empty($arr_option['field'])) {
            $arr_option['field'] = $arr_common_config['field'];
        }
        if (empty($arr_option['order'])) {
            $arr_option['order'] = $arr_common_config['order'];
        }
        if (empty($arr_option['n_per_page'])) {
            $arr_option['n_per_page'] = $arr_common_config['n_per_page'];
        }
        if (empty($arr_option['api_take_num'])) {
            $arr_option['api_take_num'] = $arr_common_config['api_take_num'];
        }
        if (empty($arr_option['withCount'])) {
            $arr_option['withCount'] = $arr_common_config['withCount'];
        }
        return $arr_option;
    }


    /**
     * 查询一条数据
     *
     * @param       $query
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeGetOption($query, $arr_option = [])
    {
        $arr_option = self::config_option($arr_option);
        return $query->with($arr_option['with'])
                     ->where($arr_option['where'])
                     ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
                     ->select($arr_option['field'])
                     ->withCount($arr_option['withCount']);

    }

    /**
     * 查询一条数据
     *
     * @param       $query
     * @param int   $nId
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeFindOption($query, $arr_option = [])
    {
        $arr_option = self::config_option($arr_option);
        return $query->with($arr_option['with'])
                     ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
                     ->select($arr_option['field']);
    }


    //        /**
    //         * 删除数据
    //         *
    //         * @param      $query
    //         * @param bool $n_type
    //         *
    //         * @return mixed
    //         * @author wumengmeng <wu_mengmeng@foxmail.com>
    //         */
    //        public function scopeApiDelete($query,$n_type = false)
    //        {
    //            if($n_type === true) {
    //                //物理删除
    //                return $query->forceDelete();
    //            }
    //            else {
    //                //软删除
    //                return $query->delete();
    //            }
    //        }

    /**
     * 分页
     *
     * @param $query
     * @param $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeCommonPage($query, $arr_option = [])
    {
        $arr_option = self::config_option($arr_option);
//        return $query->with($arr_option['with'])
//                     ->where($arr_option['where'])
//                     ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
//                     ->select($arr_option['field'])
//                     ->withCount($arr_option['withCount'])
//                     ->paginate($arr_option['n_per_page']);
        return self::scopeGetOption($query,$arr_option)->paginate($arr_option['n_per_page']);
    }


    /**
     * 分页-api
     *
     * @param $query
     * @param $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeApiPage($query, $arr_option = [])
    {
        $arr_option = self::config_option($arr_option);
        //        return $query->with($arr_option['with'])
        //                     ->where($arr_option['where'])
        //                     ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
        //                     ->select($arr_option['field'])
        //                     ->paginate($arr_option['n_per_page']);
        return self::scopeGetOption($query,$arr_option)->paginate($arr_option['api_take_num']);


    }


    /**
     * 获取所有数据
     *
     * @param $query
     * @param $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeCommonGet($query, $arr_option = [])
    {
        $arr_option = self::config_option($arr_option);
        return $query->with($arr_option['with'])
                     ->where($arr_option['where'])
                     ->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
                     ->select($arr_option['field'])
                     ->get();
    }

    /**
     * 查询一条数据
     *
     * @param       $query
     * @param int   $nId
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeCommonFind($query, int $nId, $arr_option = [])
    {
        $arr_option = self::config_option($arr_option);
        return $query->with($arr_option['with'])
                     ->select($arr_option['field'])
                     ->find($nId);
    }

    /**
     * 查询一条数据
     *
     * @param       $query
     * @param int   $nId
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeCommonFirst($query, $arr_option = [])
    {
        $arr_option = self::config_option($arr_option);
        return $query->orderBy($arr_option['order']['key'], $arr_option['order']['value'])
                     ->with($arr_option['with'])
                     ->select($arr_option['field'])
                     ->first();
    }


    /**
     * 删除数据
     *
     * @param $query
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeCommonDelete($query, bool $bool = false)
    {
        if ($bool === true) {
            //物理删除
            return $query->forceDelete();

        }
        else {
            //软删除
            return $query->delete();
        }
    }



    /**
     * 批量更新
     *
     * @param       $query
     * @param array $multipleData 批量更新数据
     *
     * @return bool|int
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function scopeUpdateBatch($query, Array $multipleData = [])
    {
        try {

            if (empty($multipleData)) {
                return 0;
                //                return hello_error('数据不能为空');
                //                die('数据不能为空');
            }
            $tableName = DB::getTablePrefix() . $this->getTable(); // 带表前缀的表名
            $firstRow  = current($multipleData);

            $updateColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);
            // 拼接sql语句
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets      = [];
            $bindings  = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql     .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn   = collect($multipleData)
              ->pluck($referenceColumn)
              ->values()
              ->all();
            $bindings  = array_merge($bindings, $whereIn);
            $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";

            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            dd($e->getMessage());
            return false;
        }
    }

    public function scopeBasicWherein($query,$arr_wherein = []){

        return $query->where(
          function($qq)
          use($arr_wherein) {
              if(count($arr_wherein) > 0){
                  foreach ($arr_wherein as $key=>$value)
                  {
                      if(count($value) > 0){
                          $qq->whereIn($key,$value);
                      }

                  }
              }

          }
        );
    }

}
